package com.lagou.xsq_springboot_rpc_consumer.proxy;

import com.alibaba.fastjson.JSON;
import com.lagou.xsq_springboot_rpc_common.model.RpcRequest;
import com.lagou.xsq_springboot_rpc_consumer.consumer.UserClientHandler;
import com.lagou.xsq_springboot_rpc_consumer.rpc.RpcClient;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @ClassName XsqProxyFactory
 * @Description TODO
 * @Author xsq
 * @Date 2020/5/30 11:19
 **/
public class XsqProxyFactory {


    private ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

    /**
     * jdk动态代理
     *
     * @param serviceClass
     * @return
     */
    public Object createProxy(final Class<?> serviceClass) {
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class<?>[]{serviceClass}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                //构建请求对象
                RpcRequest rpcRequest = RpcRequest.build(serviceClass, method, args);
                //初始化rpc调用客户端
                UserClientHandler userClientHandler = RpcClient.initClient("localhost", 8085);
                userClientHandler.setPara(rpcRequest);
                String rs = (String) executor.submit(userClientHandler).get();
                return rs;
            }
        });
    }


}
